﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.Status;
using Microsoft.Win32;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;

namespace Senthil.Mobile.WhereAmI
{
    // NOT THREAD SAFE
    public class LocationChangeNotifier : ILocationChangeNotifier
    {
        SystemState cellBroadcastChanged;
        public event EventHandler<LocationChangeNotificationEventArgs> LocationChanged;
        
        AutoResetEvent cellTowerDataReturned = new AutoResetEvent(false);
        string currentCellId = "";

        bool initialized = false;

        Timer minuteTimer;
        readonly TimeSpan period = TimeSpan.FromMinutes(1);

        #region ILocationChangeNotifier Members

        public static bool IsDeviceLocationChangeNotificationEnabled()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"ControlPanel\CellBroadcast"))
                {
                    return ((int)key.GetValue("Enable") == 1);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Initialize()
        {
            minuteTimer = new Timer(PeriodicLocationWatch, null, TimeSpan.Zero, period);

            TryRaiseLocationChanged(SystemState.PhoneCellBroadcast);

            if (initialized)
                return;

            cellBroadcastChanged = new SystemState(SystemProperty.PhoneCellBroadcast, true);
            cellBroadcastChanged.Changed += new ChangeEventHandler(cellBroadcastChanged_Changed);

            initialized = true;
        }

        void cellBroadcastChanged_Changed(object sender, ChangeEventArgs args)
        {
            TryRaiseLocationChanged((string)args.NewValue);
        }

        object lockObj = new object();

        private void TryRaiseLocationChanged(string location)
        {
            lock (lockObj)
            {
                string previousCellTowerId = currentCellId;
                string newCellTowerId = GetCellTowerId();

                if (ShouldRaiseLocationChange(location, newCellTowerId, previousCellTowerId))
                {
                    RaiseLocationChanged(location, newCellTowerId);
                }
            }
        }
        
        private void RaiseLocationChanged(string p, string cellId)
        {
            if (LocationChanged != null)
                LocationChanged(this, new LocationChangeNotificationEventArgs(p, cellId));
        }

        private bool ShouldRaiseLocationChange(string location, string newId, string oldId)
        {
            if (string.IsNullOrEmpty(location) && string.IsNullOrEmpty(newId))
                return false;

            if (string.IsNullOrEmpty(newId) && string.IsNullOrEmpty(oldId))
                return true;

            return newId != oldId;
        }

        private string GetCellTowerId()
        {
            IntPtr handleToRIL = IntPtr.Zero;
            try
            {
                var result = RIL_Initialize(1, new RILRESULTCALLBACK(RILResultCallback), null, 0, 0, out handleToRIL);

                if (result != IntPtr.Zero || handleToRIL == IntPtr.Zero)
                    return "";

                result = RIL_GetCellTowerInfo(handleToRIL);

                // If the RIL call succeeds, wait for the result, otherwise don't bother.
                if (result.ToInt32() >= 0)
                {
                    cellTowerDataReturned.WaitOne();
                }

                return currentCellId;
            }
            finally
            {
                if (handleToRIL != IntPtr.Zero)
                {
                    RIL_Deinitialize(handleToRIL);
                }
            }
        }

        private void PeriodicLocationWatch(object state)
        {
            try
            {
                minuteTimer.Change(Timeout.Infinite, Timeout.Infinite);
                TryRaiseLocationChanged((string)SystemState.PhoneCellBroadcast);
                minuteTimer.Change(period, period);
            }
            catch(Exception e)
            {
                CrashHandler.HandleCrash(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, e);
                throw;
            }
        }

        void RILResultCallback(uint dwCode, IntPtr hrCmdID, IntPtr lpData, uint cbData, uint dwParam)
        {
            try
            {
                RILCELLTOWERINFO cellTowerInfo = new RILCELLTOWERINFO();

                if (lpData == IntPtr.Zero)
                    return;

                Marshal.PtrToStructure(lpData, cellTowerInfo);

                currentCellId = cellTowerInfo.dwCellID + "_" + cellTowerInfo.dwLocationAreaCode;
            }
            finally
            {
                cellTowerDataReturned.Set();
            }
        }

        public void Dispose()
        {
            if (cellBroadcastChanged != null)
            {
                cellBroadcastChanged.Dispose();
            }

            if (minuteTimer != null)
                minuteTimer.Dispose();
        }

        #endregion

        [DllImport("ril.dll")]
        private static extern IntPtr RIL_Initialize(uint dwIndex, RILRESULTCALLBACK pfnResult,
                RILNOTIFYCALLBACK pfnNotify, uint dwNotificationClasses,
                uint dwParam, out IntPtr lphRil);
        [DllImport("ril.dll", EntryPoint = "RIL_GetCellTowerInfo")]
        private static extern IntPtr RIL_GetCellTowerInfo(IntPtr hRil);
        [DllImport("ril.dll", EntryPoint = "RIL_Hangup")]
        private static extern IntPtr RIL_Hangup(IntPtr hRil);
        [DllImport("ril.dll")]
        private static extern IntPtr RIL_Deinitialize(IntPtr hRil);

        delegate void RILRESULTCALLBACK(uint dwCode,
                                               IntPtr hrCmdID,
                                               IntPtr lpData,
                                               uint cbData,
                                               uint dwParam);
        delegate void RILNOTIFYCALLBACK(uint dwCode,
                                                       IntPtr lpData,
                                                       uint cbData,
                                                       uint dwParam);
        class RILCELLTOWERINFO
        {
            public uint cbSize;
            public uint dwParams;
            public uint dwMobileCountryCode;
            public uint dwMobileNetworkCode;
            public uint dwLocationAreaCode;
            public uint dwCellID;
            public uint dwBaseStationID;
            public uint dwBroadcastControlChannel;
            public uint dwRxLevel;
            public uint dwRxLevelFull;
            public uint dwRxLevelSub;
            public uint dwRxQuality;
            public uint dwRxQualityFull;
            public uint dwRxQualitySub;
            public uint dwIdleTimeSlot;
            public uint dwTimingAdvance;
            public uint dwGPRSCellID;
            public uint dwGPRSBaseStationID;
            public uint dwNumBCCH;
        }

    }
}
